package com.exit66.jukebox.servlet.xml;

import javax.servlet.http.HttpServletRequest;

import com.exit66.jukebox.data.Artist;
import com.exit66.jukebox.data.ArtistCollection;
import com.exit66.jukebox.Options;
import com.exit66.jukebox.util.XmlSegment;

public class ArtistListServlet extends XmlResponseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7306229432550897934L;

	protected void buildXml(HttpServletRequest req, XmlSegment xml) {
		String[] params;
		if (req.getPathInfo() != null)
			params = req.getPathInfo().split("/");
		else
			params = new String[0];
        if ((params.length >= 2) && (Options.isInteger(params[1]))) {
            try {
                Artist artist = new Artist();
                artist.setArtistID(new Integer(params[1]).intValue());
                artist.fetch();
                
                xml.appendSegment(artist.returnXml(false));
            }
            catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
        else {
            ArtistCollection list = new ArtistCollection();
            Artist artist = null;
            int start = 0;
            int count = 0;
            
            if (req.getParameter("start") != null) 
            	start = Integer.parseInt(req.getParameter("start"));
            if (req.getParameter("count") != null) 
            	count = Integer.parseInt(req.getParameter("count"));
                    
            if (params.length > 1) {
                list.list(params[1], start, count);
            } else {
                list.list("", start, count);
            }
            
            while (!list.isEOF()) {
                artist = (Artist)list.getCurrent();
                xml.appendSegment(artist.returnXml(false));
                list.moveNext();
            }
        }
		
	}

}
